<?php
declare (strict_types = 1);

namespace app\common;

use think\Config;
use Predis\Client;

/**
 * Redis管理类
 */
class RedisManager
{
    private static $instances = [];
    
    /**
     * 获取Redis连接实例
     */
    public static function getInstance($connection = 'default')
    {
        if (!isset(self::$instances[$connection])) {
            
            // 获取Redis配置，优先从cache配置中获取
            $cacheConfig = Config::get('cache');
            if ($cacheConfig && isset($cacheConfig['type']) && $cacheConfig['type'] === 'redis') {
                $config = [
                    'host' => $cacheConfig['hostname'] ?? '127.0.0.1',
                    'port' => $cacheConfig['port'] ?? 6379,
                    'password' => $cacheConfig['password'] ?? '',
                    'database' => 0,
                    'timeout' => 0,
                    'persistent' => false,
                    'prefix' => $cacheConfig['prefix'] ?? 'park_admin:',
                ];
            } else {
                // 默认配置
                $config = [
                    'host' => '127.0.0.1',
                    'port' => 6379,
                    'password' => '',
                    'database' => 0,
                    'timeout' => 0,
                    'persistent' => false,
                    'prefix' => 'park_admin:',
                ];
            }
            
            try {
                // Predis连接参数
                $parameters = [
                    'scheme' => 'tcp',
                    'host' => $config['host'],
                    'port' => $config['port'],
                    'database' => $config['select'] ?? $config['database'] ?? 0,
                ];
                
                if (!empty($config['password'])) {
                    $parameters['password'] = $config['password'];
                }
                
                if ($config['timeout'] > 0) {
                    $parameters['timeout'] = $config['timeout'];
                }
                
                // Predis选项
                $options = [];
                
                // 设置前缀
                if (!empty($config['prefix'])) {
                    $options['prefix'] = $config['prefix'];
                }
                
                $redis = new Client($parameters, $options);
                
                // 测试连接
                $redis->ping();
                
            } catch (\Exception $e) {
                throw new \Exception('Redis连接失败: ' . $e->getMessage());
            }
            
            self::$instances[$connection] = $redis;
        }
        
        return self::$instances[$connection];
    }
    
    /**
     * 测试Redis连接
     */
    public static function testConnection($connection = 'default')
    {
        try {
            $redis = self::getInstance($connection);
            $result = $redis->ping();
            return $result === '+PONG' || $result === 'PONG';
        } catch (\Exception $e) {
            return false;
        }
    }
    
    /**
     * 获取Redis信息
     */
    public static function getInfo($connection = 'default')
    {
        try {
            $redis = self::getInstance($connection);
            return $redis->info();
        } catch (\Exception $e) {
            return false;
        }
    }
    
    /**
     * 清理指定前缀的缓存
     */
    public static function clearCache($pattern = '*', $connection = 'default')
    {
        try {
            $redis = self::getInstance($connection);
            $keys = $redis->keys($pattern);
            if (!empty($keys)) {
                // PHP Redis扩展的del方法支持多个参数或数组
                // 使用数组方式更安全，避免参数过多的问题
                return $redis->del($keys);
            }
            return 0;
        } catch (\Exception $e) {
            return false;
        }
    }
}